<script setup lang="ts">
import { ref } from 'vue'
import { onLoad, onShow } from '@dcloudio/uni-app'
import { showModal } from '@uni-helper/uni-promises'
import CustomTitlePlaceholder from '@/components/CustomTitlePlaceholder.vue'
import { jsonToParams, paramsToJson, toast } from '@/utils/utils'
import user from '@/composables/user'
import { getCompanyName, getLongInsureInfo, getPayProject, getQrcodeCache, joinPayAddress, joinPayProject, joinPeriodInsure } from '@/api/project'
import { goRegisterAndBack } from '@/utils/user'
import CustomerService from '@/components/CustomerService.vue'
import CustomButton from '@/components/CustomButton.vue'
import globalVariable from '@/utils/globalVariable'
import type { PayProjectDto } from '@/api/project/type'

const scene = ref('')
const path = ref('')
const companyName = ref('')
const companyId = ref()
const projectName = ref('')
const projectId = ref()
const serveCompanyName = ref('')
const buttonText = ref('加入项目')
const titleText = ref('')
const isContract = ref(false)
const titleTips = ref('')
const projectInfo = ref<PayProjectDto>({} as PayProjectDto)
const longitude = ref()
const latitude = ref()
const coord = ref()

let callback = new Function() as () => void

function initJoin() {
    console.log('homePath', globalVariable.homePath, 'scene', scene.value)

    if (globalVariable.homePath) {
        pathJoin(globalVariable.homePath)
        globalVariable.homePath = ''
    }
    else if (scene.value) {
        pathJoin(scene.value)
    }
}

async function pathJoin(path: string) {
    const option = paramsToJson(path)
    console.log(999, option)

    if (option.type)
        onNext()

    if (option.cacheId) {
        let res = await getQrcodeCache({
            key: Number(option.cacheId),
        })
        if (res.includes('scene%3D'))
            res = decodeURIComponent(res)

        const scene = res?.split('&scene=')[1]
        pathJoin(scene)
    }
    else if (option.PCID) {
        // 加入通讯录
        joinCompanyAddress(Number(option.PCID), Number(option.UID))
    }
    else if (option.PPID) {
        // 加入发薪项目
        joinPaySalaryProject(Number(option.PPID), Number(option.UID), Number(option.ADDT))
    }
    else if (option.INID && option.UID) {
        // 加入日日保项目
        joinInsurance(Number(option.INID), Number(option.UID), Number(option.coord), option.authenticateNumber)
    }
    else if (option.LIKey) {
        // 加入长期保项目
        joinLongInsure(option.LIKey, Number(option.Id), onNext)
    }
    else if (option.tJ) {
        // 跳转快招
        const query = {
            id: option.id,
            uid: option.uid,
            force: option.force,
        }
        uni.navigateTo({
            url: `/package-mine/pages/job-detail/job-detail?${jsonToParams(query)}`,
        })
    }
    else {
        showModal({
            content: '请使用正确的小程序码',
            confirmText: '确定',
            showCancel: false,
        })
    }
}

/**
 * 加入公司通讯录
 *
 * @param companyId 公司ID
 * @param userId 用户ID
 * @returns 无返回值
 */
async function joinCompanyAddress(companyId: number, userId: number) {
    await isNeedLogin(companyId)
    const res = await getCompanyName({
        companyId,
    })
    companyName.value = res.companyName
    buttonText.value = '返回'
    callback = () => {
        uni.switchTab({
            url: '/pages/clock/clock',
        })
    }
    const addressRes = await joinPayAddress({
        companyId,
        createUserId: userId,
    })
    goSuccess('加入通讯录成功！', '', 'success')
}

/**
 * 加入发薪项目
 *
 * @param projectId 支付项目ID
 * @param userId 用户ID
 * @param type 加入类型
 * @returns 无返回值
 */
async function joinPaySalaryProject(projectId: number, userId: number, type: number = 0) {
    const res = await getPayProject({
        id: projectId,
    })
    projectInfo.value = res

    if (res?.params?.isJoinProject) {
        projectName.value = res.projectName
        companyName.value = res.companyName
        serveCompanyName.value = res.serveCompanyName
        titleText.value = '您已加入过此项目'
        buttonText.value = '返回'
        callback = async () => {
            const event = await uni.switchTab({
                url: '/pages/clock/clock',
            })
            console.log(event)
        }
        return
    }

    if (res.wesureState !== 0) {
        projectName.value = res.projectName
        companyName.value = res.companyName
        serveCompanyName.value = res.serveCompanyName
        buttonText.value = '该项目已过期'
        return
    }

    const age = getCardAge(user.userInfo.value.idCardNo)
    const sex = user.userInfo.value.sex
    // 0 男 1女
    if ((sex === '0' && user.userInfo.value.userId && res.ageRange && outOfAge(age, res.ageRange))
      || (sex === '1' && user.userInfo.value.userId && res.ageRangeFemale && outOfAge(age, res.ageRangeFemale))) {
        buttonText.value = '返回'
        titleText.value = '加入失败'
        titleTips.value = '年龄不符合要求，请咨询领队'
        callback = () => {
            uni.switchTab({
                url: '/pages/clock/clock',
            })
        }
        return
    }

    await isNeedLogin(res.companyId, res.type)

    await handleJoinPayProject(userId, user.userInfo.value.userId, projectId)

    projectName.value = res.projectName
    serveCompanyName.value = res.serveCompanyName
    buttonText.value = '返回'
    callback = () => {
        uni.switchTab({
            url: '/pages/clock/clock',
        })
    }

    !type ? goSuccess('加入项目成功', `加入项目【${res.projectName}】成功！`, 'success') : goRecruitSuccess('加入项目成功!', `加入项目【${res.projectName}】成功！`, 'success')
}

/**
 * 判断年龄是否不在指定范围内
 *
 * @param age 年龄
 * @param ageRange 年龄范围，格式为 "min-max"
 * @returns 返回布尔值，表示年龄是否超出指定范围
 */
function outOfAge(age: number, ageRange: string) {
    return (age < Number(ageRange.split('-')[0]) || age > Number(ageRange.split('-')[1]))
}

function isNeedLogin(companyId = 0, type = 0, companyName = '', projectName = '', projectId = 0) {
    return new Promise(async (resolve, reject) => {
        await user.waitLogin().catch(() => {
            globalVariable.companyId = companyId
            globalVariable.companyName = companyName
            globalVariable.projectName = projectName
            globalVariable.projectId = projectId
            globalVariable.homePath = scene.value + encodeURIComponent(`$type=${type}`)
            goRegisterAndBack(true, `/pages/join/join?scene=${encodeURIComponent(scene.value)}`)
            reject(new Error('false'))
        })
        resolve(true)
    })
}
async function goSuccess(title = '', content = '', type = '') {
    const event = await uni.reLaunch({
        url: `/package-clock/pages/success/success?title=${title}&content=${content}&type=${type}&color=#04CD5A`,
    })
}

async function goRecruitSuccess(title = '', content = '', type = '') {
    const query = {
        title,
        content,
        type,
        color: '#04CD5A',
    } as AnyObject
    if (projectInfo.value.companyId)
        query.id = projectInfo.value.companyId || 6

    uni.reLaunch({
        url: `/pages/job-status/job-status?${jsonToParams(query)}`,
    })
}

/**
 * 处理加入发薪项目的请求
 *
 * @param userId 创建用户ID
 * @param uid 用户ID
 * @param projectId 项目ID
 * @param joinType 加入类型，默认为0
 * @returns 返回Promise，成功时resolve为true，失败时reject为Error对象
 */
async function handleJoinPayProject(userId: number, uid: number, projectId: number, joinType: number = 0) {
    return new Promise(async (resolve, reject) => {
        await joinPayProject({
            createUserId: userId,
            userId: uid,
            projectId,
            joinType,
        }).catch(async (err) => {
            if (err.data.code === 500) {
                buttonText.value = '返回'
                titleText.value = '加入失败'
                titleTips.value = err.data.msg
                callback = () => {
                    uni.switchTab({
                        url: '/pages/clock/clock',
                    })
                }
                return
            }
            if (err.data.data === 'checkAge') {
                await wait(1500)
                uni.switchTab({
                    url: '/pages/clock/clock',
                })
            }
            reject(new Error('加入失败'))
        })
        resolve(true)
    })
}

/**
 * 加入保险项目
 *
 * @param insuranceId 保险项目ID
 * @param userId 用户ID
 * @param coordinate 坐标
 * @param authenticateNumbe 验证码（默认为空字符串）
 * @returns 无返回值
 */
async function joinInsurance(insuranceId: number, userId: number, coordinate: number, authenticateNumbe = '') {
    await getPosition()
    const res = await getPayProject({
        id: insuranceId,
    })
    projectId.value = res.id

    await isNeedLogin(res.companyId, res.type, res.serveCompanyName, res.projectName, insuranceId)
    if (!res.isOpenWesure) {
        joinPaySalaryProject(insuranceId, userId)
        return
    }
    if (res.params.isJoinProject) {
        projectName.value = res.projectName
        companyName.value = res.companyName
        serveCompanyName.value = res.serveCompanyName
        titleText.value = '您已加入过此项目'
        buttonText.value = '返回'
        callback = () => {
            uni.switchTab({
                url: '/pages/clock/clock',
            })
        }

        if (!res.params.isAuthed)
            // 已加入项目但未核实
            queryRelations(res.companyId)

        return
    }

    if (res.wesureState !== 0) {
        projectName.value = res.projectName
        companyName.value = res.companyName
        serveCompanyName.value = res.serveCompanyName
        buttonText.value = '该项目已过期'
        return
    }

    projectId.value = insuranceId
    projectName.value = res.projectName
    companyName.value = res.companyName
    companyId.value = res.companyId
    serveCompanyName.value = res.serveCompanyName
    coord.value = coordinate

    await handleJoinPayProject(userId, user.userInfo.value.userId, insuranceId)

    projectName.value = res.projectName
    serveCompanyName.value = res.serveCompanyName
    buttonText.value = '返回'
    callback = () => {
        uni.switchTab({
            url: '/pages/clock/clock',
        })
    }
}

/**
 * 获取当前位置信息
 *
 * @returns 返回一个Promise对象，resolve时返回true，reject时返回错误信息
 */
async function getPosition() {
    return new Promise(async (resolve, reject) => {
        // ifdef MP-ALIPAY
        const res = await my.getLocation({
            type: 1,
        })
            .catch(async (err) => {
                console.log(err)
                const res = await uni.showModal({
                    title: '温馨提示',
                    content: '小程序将获取您的授权用来显示位置信息,进行打卡操作',
                })
                if (res?.confirm) {
                    const res = await uni.openSetting({}).catch(() => {
                        toast('授权获取失败，无法打开，请确认后再试')
                        reject(new Error('授权失败'))
                    })
                    console.log(1000, res)
                    if (res.authSetting.location)
                        return getPosition()

                    toast('授权获取失败，无法打开，请确认后再试')
                    reject(new Error('授权失败'))
                }
                if (res?.cancel) {
                    toast('您已取消授权，无法打开，请确认后再试')
                    reject(new Error('授权失败'))
                }
            }) as {
            latitude: number
            longitude: number
        }

        if (res) {
            longitude.value = res.longitude
            latitude.value = res.latitude
            resolve(true)
        }
        // endif

        // .catch(async (error) => {
        //     console.log(1111, error)
        //     const res = await uni.showModal({
        //         title: '温馨提示',
        //         content: '小程序将获取您的授权用来显示位置信息,进行打卡操作',
        //     })

        // })
    })
}

function queryRelations(id: number) {
    toast('项目未核实')
}

/**
 * 加入长期保险
 *
 * @param key 密钥
 * @param id 公司计划ID
 * @param callback 回调函数
 */
async function joinLongInsure(key: string, id: number, callback: Function) {
    await isNeedLogin()
    const res = await getLongInsureInfo({
        companyPlanId: id,
    })
    titleText.value = '投保信息登记'
    buttonText.value = '立即登记'
    callback = () => {
        return new Promise(async () => {
            await joinPeriodInsure({
                key,
                id,
            })
            res.companyId ? goRecruitSuccess('登记成功', '', 'success') : goSuccess('登记成功', '', 'success')
        })
    }

    callback?.()
}

function onNext() {
    shake(callback)
}

onShow(async () => {
    await user.waitLogin().catch((err) => {
        console.log('err', err)
        goRegisterAndBack(true, `/pages/join/join?scene=${encodeURIComponent(scene.value)}`)
    })
    // console.log('userId', user.userInfo?.value?.userId)
    initJoin()
})

onLoad(async (options) => {
    console.log(11111, options)

    if (options?.scene)
        scene.value = options.scene
})
</script>

<template>
    <NavbarContainer>
        <view class="h-screen w-full">
            <image class="fixed left-0 top-0 w-full" src="../../static/images/bg.png" />
            <CustomTitlePlaceholder />
            <view class="relative z-1 mt-190rpx box-border px-30rpx lh-70rpx">
                <view v-if="!titleText" class="my-190rpx">
                    <view class="text-56rpx font-bold" @click="getPosition">成功加入</view>
                    <view class="mt-10rpx text-44rpx font-400">
                        {{ projectName ? '项目' : '' }} {{ projectName || companyName || serveCompanyName }}{{ companyName
                            ? '项目'
                            : '' }}
                    </view>
                </view>
                <view v-if="!titleText && !isContract" class="h-8rpx w-50rpx bg-#202536" />
                <image v-if="titleText && !titleTips" class="mx-auto mb-30rpx h-500rpx w-506rpx"
                       src="../../static/images/clock/img.png" />
                <view v-if="titleText" class="flex flex-col items-center">
                    <view class="max-w-458rpx text-center text-46rpx font-bold">{{ titleText }}</view>
                </view>
            </view>
            <view class="px-30rpx py-40rpx">
                <view v-if="!isContract">
                    <view v-if="projectName && !titleTips" class="my-40rpx text-lg">
                        <view class="text-textgray">项目名称：</view>
                        <view class="mt-30rpx flex items-center">
                            <image class="mr-20rpx h-40rpx w-40rpx" src="../../static/images/clock/company.png" />
                            <view class="font-500">{{ projectName }}</view>
                        </view>
                    </view>
                    <view v-if="serveCompanyName && !titleTips" class="my-40rpx text-lg">
                        <view class="text-textgray">派遣单位：</view>
                        <view class="mt-30rpx flex items-center">
                            <image class="mr-20rpx h-40rpx w-40rpx" src="../../static/images/clock/company.png" />
                            <view class="font-500">{{ serveCompanyName }}</view>
                        </view>
                    </view>
                    <view v-if="companyName" class="my-40rpx text-lg">
                        <view class="text-textgray">所属公司：</view>
                        <view class="mt-30rpx flex items-center">
                            <image class="mr-20rpx h-40rpx w-40rpx" src="../../static/images/clock/company.png" />
                            <view class="font-500">{{ companyName }}</view>
                        </view>
                    </view>
                </view>
                <view class="mb-20rpx mt-60rpx">
                    <CustomButton width="460rpx" @click="onNext">{{ buttonText }}</CustomButton>
                </view>
                <view class="mt-30rpx pb-safe-20rpx">
                    <CustomerService />
                </view>
            </view>
        </view>
    </NavbarContainer>
</template>

<style scoped></style>

<route lang="json">
{
    "style": {
        "mp-alipay": {
            "transparentTitle": "always"
        }
    }
}
</route>
